<?php

/**
 * 地区操作类
 *
 * @author karl <karl.tang@aiyuangong.com>
 * @link http://www.aiyuangong.com
 */
use think\Cache;
use think\Db;

class Area
{

    public static function getData()
    {
        // 缓存中有数据则返回
        if ($data = Cache::get('area')) {
            return $data;
        }

        // 查库
        $data = array();
        $area_all_array = Db::name('area')->select();
        foreach ((array) $area_all_array as $a) {
            $data['name'][$a['area_id']] = $a['area_name'];
            $data['parent'][$a['area_id']] = $a['area_parent_id'];
            $data['children'][$a['area_parent_id']][] = $a['area_id'];

            if ($a['area_deep'] == 1 && $a['area_region'])
                $data['region'][$a['area_region']][] = $a['area_id'];
        }

        Cache::tag('area')->set('area', $data);

        return $data;
    }
    
    public static function getDataForJs($version = 0)
    {
        set_time_limit(0);
        // 缓存中有数据则返回
        $data = Cache::get('area_js_data');
        if (!$data) {
            $data = Db::name('area')->where('area_code < 440000')->order('area_code asc')->column('area_deep,area_name,area_id,area_py', 'area_code');
            Cache::tag('area')->set('area_js_data', $data);
        }
        
        $str = [];
        foreach ($data as $data) {
            $str[] = implode('', array_values($data));
        }
        
        $version = config('area_js_version') ? : date("ymd");
        
        return "var WYAreaData = '".implode('', $str)."';WYAreaConfig.version = '".$version."';";
    }   
    
    public static function getDbData()
    {
        // 缓存中有数据则返回
        if ($data = Cache::get('area_db')) {
            return $data;
        }
        // 查库
        $data = array();
        $data = Db::name('area')->field('area_id, area_name, area_parent_id, area_sort, area_deep')->select();
        Cache::tag('area')->set('area_db', $data);
        return $data;
    }
}
